package logic

import (
	"context"
	"errors"
	"we-chat-mgr/models/cache"
	"we-chat-mgr/models/mysql"
	"we-chat-mgr/pkg"

	"we-chat-mgr/wechatrpc/internal/svc"
	"we-chat-mgr/wechatrpc/wechatrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *wechatrpc.RegisterRequest) (*wechatrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	var findUser mysql.User
	err := findUser.FindUserByTel(mysql.DB, in.Tel)
	if err != nil {
		return nil, err
	}
	if findUser.ID != 0 {
		return nil, errors.New("该手机号已被占用,请重试")
	}

	result, _ := cache.Rdb.Get(l.ctx, "smsCode_"+in.Tel).Result()
	if result != in.SmsCode {
		return nil, errors.New("短信验证码不正确,请重试")
	}

	user := &mysql.User{
		Tel:       in.Tel,
		Password:  pkg.Md5(in.Password),
		HeadImage: in.HeadImage,
		NickName:  in.NickName,
		Address:   in.Address,
	}
	err = user.UserAdd(mysql.DB)
	if err != nil {
		return nil, err
	}

	return &wechatrpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
